@ECHO OFF

SET SolutionDir=%~1
SET DevEnvDir=%~2

ECHO Prepare for sn.exe execution
call "%DevEnvDir%..\..\VC\vcvarsall.bat" x86

REM *******************************************
REM * Generate a key for signing if none exists
REM *******************************************

IF NOT EXIST "%SolutionDir%signing.snk" (    
    ECHO "Generating a key for signing ... "
    sn -k "%SolutionDir%signing.snk"
    ECHO Generated "%SolutionDir%signing.snk" for signing.
)

REM **************************************************
REM * Recreate the 'GoogleKeyContainer' key container 
REM **************************************************

ECHO Recreating the 'GoogleKeyContainer' key container

sn -d GoogleKeyContainer
sn -i "%SolutionDir%signing.snk" GoogleKeyContainer

REM ****************************
REM * Extracting the public key
REM ****************************

ECHO Extracting the public key ...

sn -p "%SolutionDir%signing.snk" "%SolutionDir%signing.pub"
sn -tp "%SolutionDir%signing.pub" > "%SolutionDir%signing.txt"

REM Remove all lines except the public key value

findstr /V "M" "%SolutionDir%signing.txt" > "%SolutionDir%signing2.txt"
findstr /V "s" "%SolutionDir%signing2.txt" > "%SolutionDir%signing3.txt"

REM loop through the text file and concatenate the public key strings

SET pubkey=
SET filename=%SolutionDir%signing3.txt

SETLOCAL enabledelayedexpansion

FOR /F "tokens=1,* delims=" %%a IN (%filename%) do if '%%a%'=='' (
	ECHO %%a%
) else if '%%a%'=='.' (
    ECHO %%a%
) else (
	SET "pubkey=!pubkey!%%a"
)

SETLOCAL disabledelayedexpansion

REM output the public key on the console (for debugging purposes) 
ECHO Extracted Public Key = %pubkey%

REM ************************************************************************************************
REM * Store the public key in the InternalsVisible(..) attibutes of GlobalGoogleApisAssemblyInfo.cs
REM ************************************************************************************************

ECHO Store the public key in the InternalsVisible(..) attibutes of GlobalGoogleApisAssemblyInfo.cs

IF EXIST "%SolutionDir%Src\GlobalGoogleApisAssemblyInfo.new.cs" DEL "%SolutionDir%Src\GlobalGoogleApisAssemblyInfo.new.cs"

SET filename=%SolutionDir%Src\GlobalGoogleApisAssemblyInfo.cs

FOR /F "tokens=1,* delims==" %%a IN (%filename%) do IF '%%b'=='' (
	ECHO %%a%%b >> "%SolutionDir%Src\GlobalGoogleApisAssemblyInfo.new.cs" 
) ELSE (
	ECHO %%a=%pubkey%^"^)^] >> "%SolutionDir%Src\GlobalGoogleApisAssemblyInfo.new.cs"
)

REM apply the changes to the solution
type "%SolutionDir%Src\GlobalGoogleApisAssemblyInfo.cs" > "%SolutionDir%Src\GlobalGoogleApisAssemblyInfo.backup.cs"
type "%SolutionDir%Src\GlobalGoogleApisAssemblyInfo.new.cs" > "%SolutionDir%Src\GlobalGoogleApisAssemblyInfo.cs"